<template>
  <switch-panel v-model:checked="switcher" label="WHEN">
    <template v-for="f in options" :key="f.name">
      <el-row class="el-row">
        <el-col :span="1">
          <el-checkbox v-model="checks[f.name]" @change="onCheck(f.name, $event)" />
        </el-col>
        <el-col :span="3">{{ f.label }}</el-col>
        <el-col v-if="checks[f.name]" :span="20">
          <el-switch v-if="f.widget === 'switch'" v-model="value_[f.name]" />
          <el-checkbox-group v-else-if="f.options" v-model="value_[f.name]">
            <template v-for="op in f.options" :key="op.value">
              <el-checkbox :label="op.value">{{ op.label }}</el-checkbox>
            </template>
          </el-checkbox-group>
        </el-col>
      </el-row>
    </template>
  </switch-panel>
</template>

<script lang="ts" setup>
  import { computed, inject } from 'vue';
  import { FormFields } from '../../maker/structure';
  import { Field } from '../form';
  import SwitchPanel from '../../other/SwitchPanel.vue';
  import { WhenValue } from '../../elementUI';

  const props = defineProps<{
    modelValue?: Record<string, WhenValue | undefined>;
  }>();

  const emit = defineEmits(['update:modelValue']);

  const checks = computed<Record<string, boolean>>(() => {
    const r: Record<string, boolean> = {};
    Object.keys(props.modelValue || {}).forEach((k: string) => {
      r[k] = true;
    });
    return r;
  });

  const switcher = computed({
    get: () => !!props.modelValue,
    set: (e) => emit('update:modelValue', e ? {} : undefined)
  });

  const onCheck = (name: string, v: boolean) => {
    if (!v) delete value_.value[name];
    else value_.value[name] = undefined;
  };

  const value_ = computed({
    get: () => props.modelValue || {},
    set: (v) => {
      emit('update:modelValue', v);
    }
  });

  const fields = inject(FormFields);

  const options = computed<Field[]>(
    () =>
      fields?.value.filter(
        (f) => f.widget && !f.multi && ['switch', 'radio', 'select'].includes(f.widget)
      ) || []
  );
</script>
<style scoped>
  .el-row {
    margin-bottom: 10px;
  }
</style>
